package com.hxq.demo4;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author hxq
 * @date 2022/4/18 16:25
 */
public class InterceptorConsumer {
    public static void main(String[] args) {

        autoCommitOffset();

    }

    private static void autoCommitOffset(){

        Properties properties = setConfigInfo(true);
//        Properties properties = setConfigInfo(false);//如果不开启自动提交，也不设置手动提交，则不会提交offset,所以每次启动消费者都会消费到上一个offset的数据
        //创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        //订阅主题
        consumer.subscribe(Arrays.asList("first"));

        while (true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : records){
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            }

        }

    }

    private static Properties setConfigInfo(Boolean isAuto){
        Properties props = new Properties();
        props.put("bootstrap.servers", "212.129.155.35:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", isAuto);//是否开启自动提交 offset 功能
        props.put("auto.commit.interval.ms", "1000");//自动提交 offset 的时间间隔
        props.put("key.deserializer",
                "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer",
                "org.apache.kafka.common.serialization.StringDeserializer");
        return props;
    }
}
